package internal

import (
	"server/g"

	"github.com/name5566/leaf/gate"
)

func init() {
	skeleton.RegisterChanRPC("UpdateGameCodeBet", UpdateGameCodeBet)
	skeleton.RegisterChanRPC("UpdateGameCode", UpdateGameCode)
	skeleton.RegisterChanRPC("UpdateState", UpdateState)
	skeleton.RegisterChanRPC("NewAgent", rpcNewAgent)
	skeleton.RegisterChanRPC("CloseAgent", rpcCloseAgent)
	skeleton.RegisterChanRPC("Push", Push)
}

func rpcNewAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	_ = a
}

func rpcCloseAgent(args []interface{}) {
	a := args[0].(gate.Agent)
	if a.UserData() != nil {
		// u := a.UserData().(g.UserData)
		//退出事件
		// g.TwmjRpc.Go("CloseAgent", u.Id)
	}
}

func UpdateGameCode(args []interface{}) {
	userId := args[0].(int64)
	//gameCode := args[1].(string)
	userinfo, ok := g.Userinfo.Load(userId)
	if ok {
		userData := userinfo.(g.UserData)
		//userData.GameCode = gameCode
		userData.Agent.SetUserData(userData)
		g.Userinfo.Store(userId, userData)
	}
}

func UpdateGameCodeBet(args []interface{}) {
	userId := args[0].(int64)
	GameCodeBet := args[1].(string)
	userinfo, ok := g.Userinfo.Load(userId)
	if ok {
		userData := userinfo.(g.UserData)
		userData.GameCodeBet = GameCodeBet
		userData.Agent.SetUserData(userData)
		g.Userinfo.Store(userId, userData)
	}
}

func UpdateState(args []interface{}) {
	userId := args[0].(int64)
	state := args[1].(string)
	userinfo, ok := g.Userinfo.Load(userId)
	if ok {
		userData := userinfo.(g.UserData)
		userData.State = state
		userData.Agent.SetUserData(userData)
		g.Userinfo.Store(userId, userData)
	}
}

func Push(args []interface{}) {
	gameCode := args[1].(string)
	for _, v := range args[0].([]int64) {
		u, ok := g.Userinfo.Load(v)
		if ok {
			userData := u.(g.UserData)
			if gameCode == userData.GameCode {
				userData.Agent.WriteMsg(args[2])
			}
			// msgstr := reflect.TypeOf(args[2]).String()
			// fmt.Println("[s->c]][", msgstr, "][userid:", v, "][data:", args[1], "]")
			// if conf.Server.Debug {
			// 	msgstr := reflect.TypeOf(args[1]).String()
			// 	fmt.Println("[s->c]][", msgstr, "][userid:", v, "][data:", args[1], "]")
			// }
		}
	}
}
